<template>
  <div class="websocket">
    <basic-container>
<!--      <h5>Websocket</h5>-->
<!--      <div>-->
<!--        <el-button type="primary" @click="connect">连接</el-button>-->
<!--      </div>-->
<!--      <div>-->
<!--        <el-input v-model="content" type="textarea"></el-input>-->
<!--        <div>-->
<!--          <el-button type="success" @click="send"> 发送</el-button>-->
<!--          <el-button @click="content = undefined">清空</el-button>-->
<!--        </div>-->
<!--        <div>-->
<!--          <el-input @click="subscribe">订阅主题</el-input>-->
<!--        </div>-->
<!--      </div>-->
      <div class="row">
        <form class="navbar-form" style="margin-left:0px">
          <div class="col-md-12">
            <div>
              <label>连接状态：{{ stompClient ? '开' : '关' }}</label>
            </div>
            <div class="form-group">
              <label>WebSocket 连接：</label>
              <el-button type="primary" @click="connect">进行连接</el-button>
<!--              <button class="btn btn-primary" type="button" onclick="connect();">进行连接</button>-->
<!--              <button style="margin-left: 5px;" class="btn btn-danger" type="button" onclick="disconnect();">断开连接</button>-->
              <el-button type="danger" @click="disconnect">断开连接</el-button>
            </div>
            <div class="form-group" style="margin-left: 50px;">
              <label>订阅地址：</label>
              <input v-model="topic" type="text" class="form-control" placeholder="订阅地址">
<!--              <el-input v-model="content"></el-input>-->
            </div>
<!--            <button class="btn btn-warning" onclick="subscribeSocket();" type="button">订阅</button>-->
            <el-button style="margin-left: 5px;" type="warning" @click="subscribeSocket">订阅</el-button>
          </div>
        </form>
      </div>
      <br/>
      <div class="row" style="margin-left: 15px;">
        <div class="form-group">
          <label>发送的消息内容：</label>
          <input type="text" v-model="content" class="form-control" placeholder="消息内容">
        </div>
<!--        <button class="btn btn-info" onclick="sendMessageNoParameter();" type="button">发送</button>-->
        <el-button type="success" @click="sendMessageNoParameter">发送</el-button>
      </div>
      <br/>
      <div class="row" style="margin-left: 10px;">
        <div class="col-md-12">
          <h5 class="page-header" style="font-weight:bold">消息内容：</h5>
          <el-row v-html="dialog"></el-row>
        </div>
      </div>
    </basic-container>
  </div>
</template>
<script>
  import {mapGetters} from 'vuex'
  import socketConfig from '@/const/socket'
  import * as SockJS from 'sockjs-client'
  import Stomp from 'stomp-websocket'
  import store from '@/store'
  import {getStore} from "../../../util/store";

  export default {
    name: 'websocket',
    data() {
      return {
        topic: undefined,
        content: undefined,
        socket: undefined,
        stompClient: undefined,
        dialog: '<el-col :span="24"><div>你好啊</div></el-col><el-col :span="24"><div>你好</div></el-col>'
      }
    },

    computed: {
      ...mapGetters(['permissions'])
    },

    created() {
      this.sys_user_add = this.permissions['sys_user_add']
      this.init()
    },
    beforeDestroy() {
      console.log("关闭连接")
      this.disconnect();
    },
    methods: {
      init() {
        console.log('websocket initial')
      },

      connect() {
        const token = store.getters.access_token
        const TENANT_ID = getStore({name: 'tenantId'}) ? getStore({name: 'tenantId'}) : 'DB_0'
        // 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
        const endpoint = socketConfig.SOCKET_ENDPOINT + '?Authorization=' + token + '&TENANT-ID=' + TENANT_ID
        this.socket = new SockJS(endpoint, null, {timeout: 15000})
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(this.socket)
        // this.stompClient.debug = null
        // 向服务器发起websocket连接
        const headers = {
          'Authorization': 'Bearer ' + token,
          'TENANT-ID':  TENANT_ID
        }
        this.stompClient.connect(headers, () => {
          this.$message.success("连接成功")
          // this.autoSubscribe()
        }, (err) => {
          this.$message.error("连接失败")
          console.error("服务器错误", err);
        })
      },
      disconnect() {
        if (this.stompClient) {
          this.stompClient.disconnect(() => {
            this.$message.success("连接已断开")
          })
          console.log('Disconnected')
          this.stompClient = undefined;
        }
      },
      autoSubscribe() {
        const subscribeTopic = '/topic/restReminder'
        if (this.stompClient) {
          const that = this
          this.stompClient.subscribe(subscribeTopic, (resp) => { // 订阅服务端提供的某个topic;
            console.log('收到消息', resp.body)
            this.$notify({
              title: '休息提醒',
              type: 'warning',
              dangerouslyUseHTMLString: true,
              message: resp.body,
              position: 'bottom-right',
              offset: 60
            })
            // that.dialog = that.dialog + that.addColTag(resp.body);
          })
          console.log('订阅成功： ' + subscribeTopic)
        } else {
          this.$message.error("请先建立连接")
        }
      },
      subscribeSocket() {
        const subscribeTopic = socketConfig.SUBSCRIBE_PREFIX + this.topic
        console.log("订阅地址：", subscribeTopic);
        if (this.stompClient) {
          const that = this
          this.stompClient.subscribe(subscribeTopic, (resp) => { // 订阅服务端提供的某个topic;
            // this.$notify({
            //   title: 'topic提醒',
            //   type: 'warning',
            //   dangerouslyUseHTMLString: true,
            //   message: resp.body + '任务，请及时处理',
            //   offset: 60
            // })
            console.log('收到消息', resp.body)
            that.dialog = that.dialog + that.addColTag(resp.body);
          })
          this.$message.success('订阅成功： ' + subscribeTopic)
        } else {
          this.$message.error("请先建立连接")
        }
      },
      sendMessageNoParameter() {
        const subscribe = socketConfig.SUBSCRIBE_PREFIX + '/hello/top'
        const message = '{"destination": "' + subscribe + '", "content": "' + this.content + '"}';
        const token = store.getters.access_token
        const TENANT_ID = getStore({name: 'tenantId'}) ? getStore({name: 'tenantId'}) : 'DB_0'
        const headers = {
            'Authorization': 'Bearer ' + token,
          'TENANT-ID':  TENANT_ID
        }
        this.stompClient.send(socketConfig.SEND_ENDPOINT, headers, message);
        this.dialog = this.dialog + this.addColTag(this.content);
        this.content = '';
      },
      addColTag(content) {
        return '<el-col :span="24"><div>' + content +'</div></el-col>\n'
      }

    }
  }
</script>
<style lang="scss">

</style>